import { OnInit, OnDestroy } from '@angular/core';

import { Util } from '../../utils/util';

import { Subscription } from 'rxjs';

export class BrandBase implements OnInit {

  user:any;

  busy: Subscription;

  //http
  serivce: any;
  constructor(public util: Util, Service) {

    this.user = this.util.sessionStore().get('user');

    this.util.sortHandel(this.param);

    this.serivce = Service;

  }

  // pages data
  vm: any = {

    page: 1,
    table: {
      brands: [],
      count: 0
    }
  };

  // 参数
  param: any = {
    page: 0,
    start: 0,
    rows: 10,
    sort: 'sellMoney',
    sortType: 'desc'
  };



  // 列名
  public columns: Array<any> = [
    {
      title: '品牌名称',
      name: 'brandName',
      sort: false
    },
    {
      title: '类目',
      name: 'categoryName',
      sort: false
    },
    {
      title: '动销店铺数',
      name: 'shopNum',
      sort: true,
      class: "text-overflow"
    },
    {
      title: '动销宝贝数',
      name: 'productNum',
      sort: true,
      class: "text-overflow"
    },
    {
      title: '日销售额',
      name: 'sellMoney',
      sort: true,
      class: "text-overflow"
    },
    {
      title: '日销售量',
      name: 'sellAmount',
      sort: true,
      class: "text-overflow"
    },
    {
      title: '近30天销售额',
      name: 'monthSellMoney',
      sort: true,
      class: "text-overflow"
    },
    {
      title: '近30天销售量',
      name: 'monthSellAmount',
      sort: true,
      class: "text-overflow"
    }
  ];


  sellEvent: any;
  ngOnInit() {
  }

  ngOnDestroy() {

    console.log('destory base');

    if (this.busy) {
      this.busy.unsubscribe();
    }
    if (this.sellEvent) {
      this.sellEvent.unsubscribe();
    }


  }



  // st-sort directive emit
  sortChanged(sort) {
    console.log('xxx');
    console.log(sort);
    this.getHttp(this.param);
  }
  //分页
  pageChanged(currentPage) {

    console.log(currentPage);

    this.vm.page = currentPage;

    this.param.start = (currentPage - 1) * this.param.rows;

    this.getHttp(this.param);

  }


  // out handel
  cat: any;
  handleUpdated(cat) {

    if (!this.util.equals(this.cat, cat)) {
      this.cat = cat;

      this.param.categoryId = this.cat.id;

      console.log(cat);

      this.getHttp(this.param);
    }

  }


  getHttp(param) {


    this.busy = this.serivce.getBrand(param).subscribe((res: any) => {


      for (let i in res.data.value) {

        let item = res.data.value[i];

        item.price = this.util.avgPrice(item.sellMoney, item.sellAmount);

        item.monthPrice = this.util.avgPrice(item.monthSellMoney, item.monthSellAmount);

      }

      this.vm.table.brands = res.data.value;

      this.vm.table.count = res.data.count;

    }, (err: any) => {

    });
  }

}
